﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using Entity;

namespace BLL
{
    public class SitePrincipal : System.Security.Principal.IPrincipal
    {
        protected System.Security.Principal.IIdentity identity;
        protected IList<BoRoles> roles = new List<BoRoles>();
        protected IList<ModuleVo> modules = new List<ModuleVo>();

        private TeacherService teacherService = new TeacherService();

        public SitePrincipal(string userName)
        {
            SiteIdentity si = new SiteIdentity();
            if (!si.GetUserByName(userName))
                throw new Exception("该用户不存在！");
            if (si.UserType == 0) // Teacher
            {
                roles = teacherService.GetRolesByTeacchers(si.UserID);
            }

            identity = si;
        }



        /// <summary>
        /// 通过用户名和密码来返回sitePrincipal
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static SitePrincipal ValidateLogin(string userName, string password)
        {
            SitePrincipal sp = new SitePrincipal(userName);
            SiteIdentity si = sp.Identity as SiteIdentity;
            if (si.Password != password)
                throw new Exception("密码不匹配！");
            return sp;
        }

        public bool IsInRole(string role)
        {
            foreach (BoRoles r in roles)
            {
                if (role == r.ROL_NAME)
                    return true;
            }
            return false;
        }

        // Properties
        public System.Security.Principal.IIdentity Identity
        {
            get { return identity; }
            set { identity = value; }
        }

        public IList<BoRoles> Roles
        {
            get { return roles; }
        }
    }
}
